package com.example.serverbinder

import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.IBinder
import android.util.Log
import android.view.View
import android.widget.EditText
import android.widget.TextView

class MainActivity : AppCompatActivity() {
    lateinit var addEdit: EditText
    lateinit var removeEdit: EditText
    lateinit var text: TextView
    private var controller: IController? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        initView()
    }

    private fun initView() {
        addEdit = findViewById(R.id.addEdit)
        removeEdit = findViewById(R.id.removeEdit)
        text = findViewById(R.id.text)

        findViewById<View>(R.id.bindService).setOnClickListener {
            val intent = Intent()
            intent.setClassName(
                "com.example.serverbinder",
                "com.example.serverbinder.ServerService"
            )
            val clientConnection = ClientConnection()
            val bindService = bindService(intent, clientConnection, Context.BIND_AUTO_CREATE)
            Log.i("=====", "initView: $bindService")
        }
        findViewById<View>(R.id.addData).setOnClickListener {
            val text = addEdit.text.toString()
            val user = User()
            user.setName(text)
            controller?.add(user)
        }
        findViewById<View>(R.id.removeData).setOnClickListener {
            val index = removeEdit.text.toString().toInt()
            controller?.remove(index)
        }
        findViewById<View>(R.id.printData).setOnClickListener {
            val list = controller?.list
            text.text = list.toString()
        }
    }

    inner class ClientConnection : ServiceConnection {
        override fun onServiceConnected(p0: ComponentName?, p1: IBinder?) {
            controller = IController.Stub.asInterface(p1)
        }

        override fun onServiceDisconnected(p0: ComponentName?) {
        }
    }
}